import React, { useState, useEffect } from 'react';
import { HttpCode } from '#/utils/contacts.js';
import { ModuleHeader, ModuleCharts, Map } from '../components';
import { deviationModalData, saleTable, sellPowerMap } from '@/services/businessAnalysis';
import { queryDataPower } from '@/services/user';
import { powersDataType } from '#/utils/userHelper';
import { Spin } from 'antd';
import { TRDefault } from '@/components';
import PropTypes from 'prop-types';
import styles from './index.less';

const ElectricitySales = (props) => {
  const {
    code,
    title,
    dateObj: { startDate, endDate },
    type,
  } = props;

  let [selectRegion, setSelectRegion] = useState([]);
  let [data, setData] = useState([]);
  let [color, setColor] = useState([]);
  let [deviationList, setdeviationList] = useState([]);
  const [regionData, setRegionData] = useState([]);
  const [prowerLoading, setPowerLoading] = useState(false);
  const [dataLoading, setDataLoading] = useState(false);
  const [provinceIdList, setProvinceIdList] = useState([]);
  const [month, setMonth] = useState(1);
  let [year, setYear] = useState('');
  const [mapData, setMapData] = useState([]);

  useEffect(() => {
    getQueryDataPower();
  }, []);
  useEffect(() => {
    _onGetData();
    _deviationModal();
  }, [provinceIdList]);
  useEffect(() => {
    async function fn() {
      setSelectRegion([]);
      await setProvinceIdList([]);
      let data = regionData.map((item) => item.provinceName);
      setProvinceIdList(data);
    }
    fn();
  }, [type, startDate, endDate]);

  useEffect(() => {
    if (startDate && endDate && type && regionData.length) {
      _onGetData();
      _deviationModal();
    }
  }, [selectRegion]);
  const getQueryDataPower = async () => {
    setPowerLoading(true);
    const res = await queryDataPower(code);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setPowerLoading(false);
      let powerObj = {};
      Object.keys(powersDataType).forEach((item) => {
        powerObj[item] = res.powers.filter((n) => n.type === powersDataType[item])[0]?.json || [];
      });
      const data = (powerObj && powerObj.province_region) || [];
      setRegionData(data);
      setProvinceIdList(data.map((item) => item.provinceName));
    }
  };

  const _onSetSelectRegion = (data) => {
    setSelectRegion(data);

    data.length > 0
      ? setProvinceIdList(data.map((item) => item.provinceName))
      : setProvinceIdList(regionData.map((item) => item.provinceName));
  };

  const _onGetData = async () => {
    setDataLoading(true);
    let provinceIdList = selectRegion.length
      ? selectRegion.map((n) => n.provinceName)
      : regionData.map((item) => item.provinceName);

    if (!provinceIdList.length) {
      setDataLoading(false);
      return;
    }

    let res = await sellPowerMap({
      startDate,
      endDate,
      type,
      provinceIdList,
    });
    setDataLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      if (provinceIdList.length === regionData.length) {
        setMapData(res.resSellPowerMapBodyList);
        setColor(res.colorScaleBody);
      }
      setData(res.resSellPowerMapBodyList);
      res.month && setMonth(res.month);
      res.year && setYear(res.year);
    }
  };

  let _deviationModal = async () => {
    //偏差弹框数据
    if (!regionData.length) return;

    let res = await deviationModalData({
      endDate: endDate,
      provinceIdList: selectRegion.length
        ? selectRegion.map((n) => n.provinceName)
        : regionData.map((item) => item.provinceName),
      startDate: startDate,
      type,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setdeviationList(res.deviationAssessBody && res.deviationAssessBody.deviationAssessmentList);
    }
  };

  // if (!deviationList.length > 0) {
  //   return <div />;
  // }

  return (
    <div className={styles.transactionBox}>
      {prowerLoading ? (
        <Spin spinning={prowerLoading} style={{ width: '100%', height: 300, marginTop: 30 }} />
      ) : !prowerLoading && (!regionData || !regionData.length) ? (
        <>
          <ModuleHeader title={title} />
          <div className={styles.powerEmpty}>
            <TRDefault type="lock" />
          </div>
        </>
      ) : (
        <>
          <ModuleHeader
            title={title}
            region={{ show: true, regionData, selectRegion, setRegion: _onSetSelectRegion, code }}
          />
          <div className={styles.moduleChartDiv}>
            {!!provinceIdList.length && (
              <ModuleCharts
                startDate={startDate}
                endDate={endDate}
                type={code}
                dateType={type}
                queryAction={saleTable}
                height={{ height: 365 }}
                searchData={{
                  type,
                  startDate,
                  endDate,
                  provinceIdList,
                }}
              />
            )}
          </div>
          <Spin spinning={dataLoading}>
            <Map
              type={type}
              dateObj={{ startDate, endDate }}
              code={code}
              data={data}
              color={color}
              month={month}
              year={year}
              deviationList={deviationList}
              startDate={startDate}
              mapData={mapData}
            />
          </Spin>
        </>
      )}
    </div>
  );
};

ElectricitySales.propTypes = {
  code: PropTypes.string,
  title: PropTypes.string,
  dateObj: PropTypes.object,
  type: PropTypes.string,
};

export default ElectricitySales;
